package com.pangu.core.engine.game.task.redblack;

import java.util.ArrayList;
import java.util.List;

import org.cache2k.expiry.ValueWithExpiryTime;

import com.pangu.core.BMDataContext;
import com.pangu.core.cache.CacheHelper;
import com.pangu.core.engine.game.ActionTaskUtils;
import com.pangu.core.engine.game.BeiMiGameTask;
import com.pangu.core.engine.game.task.AbstractTask;
import com.pangu.util.GameUtils;
import com.pangu.web.model.GameRoom;
import com.pangu.web.model.PlayUser;
import com.pangu.web.model.PlayUserClient;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CreateRedBlackAITask extends AbstractTask implements ValueWithExpiryTime {

	private long timer;
	private GameRoom gameRoom = null;
	private String orgi;

	public CreateRedBlackAITask(long timer, GameRoom gameRoom, String orgi) {
		super();
		this.timer = timer;
		this.gameRoom = gameRoom;
		this.orgi = orgi;
	}

	@Override
	public long getCacheExpiryTime() {
		return System.currentTimeMillis() + timer * 1000; // 5秒后执行
	}

	/**
	 * 执行生成AI
	 */
	public void execute() {
		// 查看房间中的人数
		List<PlayUserClient> playerList = CacheHelper.getGamePlayerCacheBean().getCacheObject(gameRoom.getId(),
				gameRoom.getOrgi());
		// 移除金额为小于50 AI
		List<PlayUserClient> temp = new ArrayList<PlayUserClient>();
		for (PlayUserClient playUserClient : playerList) {
			if (playUserClient.getGoldcoins() < 50
					&& BMDataContext.PlayerTypeEnum.AI.toString().equals(playUserClient.getPlayertype())) {
				temp.add(playUserClient);
			}
		}
		playerList.removeAll(temp);

		int aicount = (gameRoom.getPlayers() - playerList.size()) / 2;// 初始化一半的ai进房间
		// 本身AI的数量
		int ai = 0;
		for (int i = 0; i < playerList.size(); i++) {
			PlayUserClient player = playerList.get(i);
			if (BMDataContext.PlayerTypeEnum.AI.toString().equals(player.getPlayertype())) {
				ai = ai + 1;
			}
		}
		if (ai > 10) {
			aicount = 0;
		}
		if (aicount > 10) {
			aicount = 10;
		}

		if (aicount > 0) {
			for (int i = 0; i < aicount; i++) {
				PlayUserClient playerUser = CacheHelper.getQuenePlayerCache().poll(gameRoom.getOrgi());
				if (playerUser == null) {
					break;
				}
				playerUser.setPlayerindex(System.currentTimeMillis()); // 按照加入房间的时间排序，有玩家离开后，重新发送玩家信息列表，重新座位
				playerUser.setRoomid(gameRoom.getId());
				playerUser.setRoomready(true);
				playerUser.setOnline(true);
				CacheHelper.getGamePlayerCacheBean().put(playerUser.getId(), playerUser, orgi); // 将用户加入到 room ，
				playerList.add(playerUser);
			}
			log.info("初始化" + playerList.size() + "名ai进入房间");
		}
	}
}
